/**
 * 
 */
package com.wayoos.wap.registry;

import java.util.EnumSet;

import org.eclipse.jetty.server.DispatcherType;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceFilter;
import com.wayoos.wap.api.Application;
import com.wayoos.wap.api.ApplicationContextAware;
import com.wayoos.wap.api.ApplicationLifecycle;
import com.wayoos.wap.api.context.WapContext;
import com.wayoos.wap.registry.test.SandwichModule;

/**
 * @author steph
 * 
 */
public class WapRegistryApplication implements Application, ApplicationContextAware,
		ApplicationLifecycle {

	private WapContext context;

	private Server server;

	@Override
	public void setContext(WapContext context) {
		this.context = context;
	}

	@Override
	public void start() {
		System.out.println("Start registry app");

		Injector injector = Guice.createInjector(new SandwichModule(), new AbstractModule() {
			@Override
			protected void configure() {
				binder().requireExplicitBindings();
				bind(GuiceFilter.class);
			}
		});

		server = new Server(context.registryPort());

		ServletContextHandler handler = new ServletContextHandler();
		handler.setContextPath("/");

		handler.addServlet(new ServletHolder(new InvalidRequestServlet()), "/*");

		FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
		handler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

		server.setHandler(handler);
		try {
			server.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Server server = new Server(8080);
		// // handlers go here
		//
		// ServletContextHandler handler = new ServletContextHandler();
		// handler.setContextPath("/");
		// // set up handler
		// server.setHandler(handler);
		//
		// try {
		// server.start();
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	@Override
	public void stop() {
		System.out.println("Stop registry app");

		try {
			server.stop();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
